package com.daydr3am.thenation;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.entity.mime.MultipartEntity;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.coe3.data.Information;
import com.coe3.data.NewData;
import com.coe3.datahandler.BaseActivity;
import com.coe3.datahandler.HttpConnection;
import com.coe3.datahandler.ParserXMLHandler;
import com.coe3.datahandler.ParserXMLHandler.ElementData;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

public class Lastest extends BaseActivity implements OnClickListener {
		
	private final int[] last_title = {R.id.last_title_1, 
			R.id.last_title_2, 
			R.id.last_title_3, 
			R.id.last_title_4, 
			R.id.last_title_5, 
			R.id.last_title_6, 
			};
	

	private final int[] last_des = {R.id.last_des_1, 
			R.id.last_des_2, 
			R.id.last_des_3, 
			R.id.last_des_4, 
			R.id.last_des_5, 
			R.id.last_des_6, 
			};
	
	private final int[] last_pub = {R.id.last_pub_1, 
			R.id.last_pub_2, 
			R.id.last_pub_3, 
			R.id.last_pub_4, 
			R.id.last_pub_5, 
			R.id.last_pub_6, 
			};
	
	
	private final int[] last_FrameLayout = {R.id.l11, 
			R.id.l12, 
			R.id.l13, 
			R.id.l21, 
			R.id.l22, 
			R.id.l23, 
			};
	
	private Activity mActivity;
	public static Lastest mInstance;
	
	private ArrayList<String> 	List_title= new ArrayList<String>();
	private ArrayList<String> 	List_des= new ArrayList<String>();
	private ArrayList<String>	List_pub= new ArrayList<String>();
	private ArrayList<String>	List_detail= new ArrayList<String>();
	
	public static Lastest getInstance() {
		//if(mInstanceLastest == null)
			mInstance = new Lastest();
			
		return mInstance;
	}
	
	public void initial(Activity activity)
	{
		this.mActivity = activity;
		LoadContent();
	}
	
	private int i=0;
	public void setData(final Lastest lastest) {
		
		new Handler().post(new Runnable() {
			
			@SuppressLint("SimpleDateFormat")
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				 i=0;
				while(i<6)
				{
					TextView title=(TextView)mActivity.findViewById(last_title[i]);
					TextView des=(TextView)mActivity.findViewById(last_des[i]);
					TextView pub=(TextView)mActivity.findViewById(last_pub[i]);
					
					title.setText(""+List_title.get(i));
					des.setText(""+List_des.get(i));
					pub.setText(""+List_pub.get(i)+"");
					
					i++;
				}
				
			}//end for
			
		});
		
		//============================DG===============================
		i=0;
		while(i<6)
		{	
		
			FrameLayout frm=(FrameLayout)mActivity.findViewById(last_FrameLayout[i]);
			frm.setOnClickListener(this);
			i++;
		}
		//=============================================================
	}
	
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		i=0;
		while(i<last_FrameLayout.length)
		{	
		
			if(v.getId()==last_FrameLayout[i])
				ShowDialog(i);
			i++;
		}
	}
	
	
	
	private void LoadContent()
	{
		
		String url="http://www.nationmultimedia.com/new/rss/ipad_v2/breakingnews.xml";
		startConnection( url, "", HttpConnection.GET, -1, null );
	}
	
	//=============================Parser===========================
	@SuppressLint("HandlerLeak")
	public void startConnection( String url, String data , int method, final int handlerType, final MultipartEntity entity ) {
		Log.e("max", "MainActivity==========startConnection");
		Log.e("chud", "url: " + url);
		Log.e("chud", "data: " + data);
		
		Handler handler = new Handler() {
			public void handleMessage(Message message) {
				switch ( message.what ) {
					case HttpConnection.DID_START:
						   
						   Log.e("max", "MainActivity==========DIALOG_CONNECTION_START");
							//showDialog( DIALOG_CONNECTION_START );
						   TheNationMain.getInstanceProgressDialong(mActivity).show();
						break;
					
					case HttpConnection.DID_SUCCEED:
						try {
							Log.e("chud", "(String)message.obj: " + (String)message.obj);
							startParseXMLResponse( (String)message.obj, handlerType );
						} catch ( Exception e ) {
							Log.e( "Connection Exception", "XML Pasing Excpetion : " + e );
			        		//didFinishParsing();
							TheNationMain.dismissProgress(mActivity);
						}
						
						break;
					
					case HttpConnection.DID_ERROR:
						Log.e( "Connection Error", "HTTP Connection did error : " + message.obj );
						BaseActivity.showAlertBox(getBaseContext(),  "Connection Error!!!", "Please try again." );
						TheNationMain.dismissProgress(mActivity);
						
						break;
				}	
			}
		};

		HttpConnection connection = new HttpConnection(handler);
		if( entity != null )
			connection.setMultipartEntity( entity );
		connection.create(method, url, data);
	}
	
	public void startParseXMLResponse( String response, int handlerType ) throws SAXException, ParserConfigurationException, IOException {
		
		Log.e("max", "MainActivity==========startParseXMLResponse");
		SAXParserFactory spf = SAXParserFactory.newInstance();
		Log.e("max", "MainActivity==========startParseXMLResponse2");
		SAXParser sp = spf.newSAXParser();
		XMLReader xr = sp.getXMLReader();
		
		ParserXMLHandler parser = null;
		Handler handler = handlerInformation(handlerType);
		parser = new ParserXMLHandler( this, handler );
	
		StringReader sr = new StringReader(response);
		InputSource is = new InputSource(sr);
		
		xr.setContentHandler(parser);
		xr.parse(is);
	}
	
	
	private NewData mItem = null;
	private static Vector<NewData> mListNews = new Vector<NewData>();
	@SuppressLint("HandlerLeak")
	public Handler handlerInformation(final int handlerType) {
		
		Log.e("max", "MainActivity==========handlerInformation");
		
		Handler mHandler = new Handler() {
			public void handleMessage( Message message ) {
				ElementData data = ( ElementData )message.obj;
				switch( message.what ) {
					case ParserXMLHandler.START_DOCUMENT:
						
						mListNews.removeAllElements();
						
						break;
						
					case ParserXMLHandler.DID_START_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mItem = new NewData();
						}//end if
						
					
						
						break;
						
					case ParserXMLHandler.DID_FINISH_ELEMENT:
						
						if( data.name.equalsIgnoreCase(NewData.TAG_TITLE) ) 
						{
							mItem.title = Information.setData(data.value, Information.STR_EMPTY);
						} 
						else if( data.name.equalsIgnoreCase(NewData.TAG_DESCRIPTION) ) 
						{
							mItem.description = Information.setData(data.value, Information.STR_EMPTY);
						}  else if( data.name.equalsIgnoreCase(NewData.TAG_PUB) ) 
						{
							mItem.pubDate = Information.setData(data.value, Information.STR_EMPTY);
						} 
						
						else if( data.name.equalsIgnoreCase(NewData.TAG_DETAIL) ) 
						{
							mItem.detail = Information.setData(data.value, Information.STR_EMPTY);
						} 
						
						else if( data.name.equalsIgnoreCase(NewData.TAG_ITEM) ) 
						{
							mListNews.add(mItem);
							mItem = null;
						}//end if
						
						break;
						
					case ParserXMLHandler.END_DOCUMENT:
						
						TheNationMain.dismissProgress(mActivity);
						
						setNews(mListNews);
					   
						break;
				}
			}
		};
			
		return mHandler;
	}
	
	
	public void setNews(Vector<NewData> listNews) {
		Log.e("max", "MainActivity==========setNews(Vector<NewData> listNews)");
		for (NewData newData : listNews) {
			Information.logDEBUG("title: " + newData.title);
			
			
			List_title.add(newData.title);
			List_des.add(newData.description);
			List_pub.add(newData.pubDate);
			List_detail.add(newData.detail);
			Log.e("max","newData.description="+ newData.title);
			setData(this);
			mInstance=null;
		}
		
	}
	
	//=========================Dialog===============================
	@SuppressWarnings("static-access")
	public void ShowDialog(int id)
	{
		Log.e("max"," ShowDialog id="+ id);
		
		 final Dialog dialog = new Dialog(mActivity,android.R.style.Theme_Translucent_NoTitleBar);
         dialog.requestWindowFeature(dialog.getWindow().FEATURE_NO_TITLE);
         dialog.setContentView(R.layout.lastest_alertdilog);
         dialog.setCancelable(true);
         dialog.setCanceledOnTouchOutside(false);
         
         TextView txt_detail=(TextView)dialog.findViewById(R.id.txt_detail);
         TextView txt_title=(TextView)dialog.findViewById(R.id.txt_title);
          
         txt_title.setText(Html.fromHtml(List_title.get(id)));
         txt_detail.setText(Html.fromHtml(List_detail.get(id)));
       
         txt_title.setTextColor(Color.parseColor("#000000"));
         txt_detail.setTextColor(Color.parseColor("#000000"));
         
         Button button1 = (Button) dialog.findViewById(R.id.btn_close);
         button1.setOnClickListener(new OnClickListener()
         
         {
             public void onClick(View v)  // OK button
             
             {	
            
                  dialog.cancel();
                   
             }
         });
         
            
         dialog.show();
	}
	
}
	
	
	
	
